import time
from datetime import datetime, timedelta

from flask import current_app, jsonify
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info.models import User, News, Category
from info.response_code import RET
from info.utils.commen import user_login_data
from info.utils.image_storage import storage
from . import admin_blu


@admin_blu.route('/news_type',methods=['get','post'])
def news_type():
    """新闻分类展示
    1.查询新闻分类
    2.返回分类数据给前端  并移除最新分类
    """
    if request.method == 'GET':
        try:
            categoires = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_type.html', errmsg='未查询到数据')

        if not categoires:
            return render_template('admin/news_type.html', errmsg='未查询到数据')

        cate_list = []
        for cate in categoires:
            cate_list.append(cate.to_dict())
        cate_list.pop(0)
        data = {
            'categories': cate_list
        }
        return render_template('admin/news_type.html', data=data)

    # 修改分类数据 增加分类 二者的区别在于前端传过来的参数中是否包含了分类id
    # 如果包含了分类id 说明是修改分类  通过分类id查找对应分类并修改保存
    data_dict = request.json
    cname = data_dict.get('name')
    cid = data_dict.get('id')
    if not cname:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 如果cid存在,说明是修改分类
    if cid:
        try:
            cate = Category.query.get(cid)
            cate.name = cname
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg='分类查询失败')
    else:
        # 如果cid不存在,说明是新增一个分类
        cate = Category()
        cate.name = cname
        db.session.add(cate)

    return jsonify(errno=RET.OK, errmsg='ok')


@admin_blu.route('/news_edit_detail', methods=['post', 'get'])
def news_edit_detail():
    """新闻版式编辑详情页
    1.请求时返回新闻的详细数据，并且分类数据要返回给前端，默认选中当前新闻的分类
    """
    if request.method == 'GET':
        # 获取当前新闻id
        news_id = request.args.get('news_id')
        if not news_id:
            return render_template('admin/news_edit_detail.html', data={"errmsg": "未查询到此新闻"})
        # 尝试查询新闻数据
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
        if not news:
            return render_template('admin/news_edit_detail.html', data={"errmsg": "未查询到此新闻"})

        # 查询分类数据
        categories_model = Category.query.all()
        categories_li = []
        for category in categories_model:
            c_dict = category.to_dict()
            # 将分类被选中的条件默认置为false
            c_dict["is_selected"] = False
            # 如果分类id和当前新闻的分类id相同，则将分类选中条件置为true
            if category.id == news.category_id:
                c_dict["is_selected"] = True
            categories_li.append(c_dict)
        # 移除最新分类
        categories_li.pop(0)
        # 将新闻数据和分类数据返回给前端
        data = {
            "news": news.to_dict(),
            "categories": categories_li
        }
        return render_template('admin/news_edit_detail.html', data=data)

    # 代码执行到此 说明是POST请求
    # 接收参数
    news_id = request.form.get("news_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")
    # 1.1 判断数据是否有值
    if not all([title, digest, content, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到新闻数据")

    # 1.2 尝试读取图片
    if index_image:
        try:
            index_image = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        # 2. 将标题图片上传到七牛
        try:
            key = storage(index_image)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key

    # 3. 设置相关数据
    news.title = title
    news.digest = digest
    news.content = content
    news.category_id = category_id

    # 4. 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
    # 5. 返回结果
    return jsonify(errno=RET.OK, errmsg="编辑成功")


@admin_blu.route('/news_edit/')
def news_edit():
    """新闻版式编辑  以通过审核的新闻
    1.返回新闻的列表 类似新闻审核页面的新闻列表
    """
    page = request.args.get('page', 1)
    keywords = request.args.get("keywords", "")
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    current_page = 1
    total_page = 1

    try:
        filters = [News.status == 0]
        # 如果有关键词
        if keywords:
            # 添加关键词的检索选项
            filters.append(News.title.contains(keywords))

        # 查询
        paginate = News.query.filter(*filters) \
            .order_by(News.create_time.desc()) \
            .paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)

        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())

    data = {"total_page": total_page, "current_page": current_page, "news_list": news_dict_list}

    return render_template('admin/news_edit.html', data=data)


@admin_blu.route('/news_review_detail', methods=['get', 'post'])
def news_review_detail():
    """新闻审核详情页
    1.请求时显示新闻详细信息
    """
    if request.method == 'GET':
        news_id = request.args.get("news_id")
        if not news_id:
            return render_template('admin/news_review_detail.html', data={"errmsg": "未查询到此新闻"})

        # 通过id查询新闻
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)

        if not news:
            return render_template('admin/news_review_detail.html', data={"errmsg": "未查询到此新闻"})

        # 返回数据
        data = {"news": news.to_dict()}
        return render_template('admin/news_review_detail.html', data=data)

    # 代码执行到此说明审核内容提交
    # 前端传过来的参数为  通过&拒绝  拒绝原因  新闻id
    data_dict = request.json
    # news_id在审核详情页的隐藏字段中
    news_id = data_dict.get('news_id')
    action = data_dict.get('action')

    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if action not in ['accept', 'reject']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    news = None
    try:
        # 查询新闻
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到数据")

        # 根据不同的状态设置不同的值
    if action == "accept":
        news.status = 0

    else:
        # 拒绝通过的原因
        reason = data_dict.get('reason')
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="没有拒绝原因")
        news.reason = reason
        news.status = -1

        # 保存数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    return jsonify(errno=RET.OK, errmsg="操作成功")


@admin_blu.route('/news_review')
def news_review():
    """新闻审核列表
    1.接收前端发过来的页数并校验
    2.分页查询新闻数据
    3.返回数据给前端
    """
    # 接收参数
    page = request.args.get('page', 1)
    keywords = request.args.get('keywords')
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 给参数默认值
    current_page = 1
    total_page = 1
    news_li = []
    # 尝试分页查询数据
    try:
        filters = [News.status != 0]
        if keywords:
            filters.append(News.title.contains(keywords))
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,
                                                                                          constants.ADMIN_USER_PAGE_MAX_COUNT,
                                                                                          False)
        current_page = paginate.page
        total_page = paginate.pages
        news_li = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    # 将模型对象转换成字典并添加到字典列表
    news_lists = []
    for news in news_li:
        news_lists.append(news.to_review_dict())
    data = {
        "current_page": current_page,
        "total_page": total_page,
        "news_list": news_lists
    }

    return render_template('admin/news_review.html', data=data)


@admin_blu.route('/user_list')
def user_list():
    """获取用户列表
    1.接收前端发过来的页数并校验
    2.分页查询用户数据
    3.返回数据给前端
    """
    # 接收参数
    page = request.args.get('page')
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 给参数默认值
    current_page = 1
    total_page = 1
    user_li = []
    # 尝试分页查询数据
    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.last_login.desc()).paginate(page,
                                                                                                       constants.ADMIN_USER_PAGE_MAX_COUNT,
                                                                                                       False)
        current_page = paginate.page
        total_page = paginate.pages
        user_li = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    # 将模型对象转换成字典并添加到字典列表
    user_lists = []
    for user1 in user_li:
        user_lists.append(user1.to_admin_dict())
    data = {
        "current_page": current_page,
        "total_page": total_page,
        "user_list": user_lists
    }

    return render_template('admin/user_list.html', data=data)


@admin_blu.route('/user_count')
def user_count():
    """用户统计"""
    # 1.总人数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 2.月新增人数  从本月一号0时0分之后创建的用户
    mon_count = 0
    # 获取当前时间
    t = time.localtime()
    # 获取本月1号的datetime格式的数据
    begin_mon_date = datetime.strptime(('%d-%02d-01' % (t.tm_year, t.tm_mon)), "%Y-%m-%d")
    try:
        # mon_count=User.query.filter(User.create_time>本月1号).count()
        mon_count = User.query.filter(User.is_admin == False, User.create_time > begin_mon_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 3.日新增人数  类似月新增人数
    day_count = 0
    # 获取当前时间
    t = time.localtime()
    # 获取本月1号的datetime格式的数据
    begin_day_date = datetime.strptime(('%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)), "%Y-%m-%d")
    try:
        # mon_count=User.query.filter(User.create_time>本月1号).count()
        day_count = User.query.filter(User.is_admin == False, User.create_time > begin_day_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 用户活跃折线图，获取三十天的用户活跃数量，存放到列表，按天数从前往后排
    # 将本日日期转成日期格式的字符串
    t1 = datetime.now().strftime('%Y-%m-%d')
    # 获取本日日期格式数据
    now_date = datetime.strptime(t1, "%Y-%m-%d")
    # 前一日的活跃开始日期为前一日的0时0分  所以日期减少一天
    # bigin_time=now_date-timedelta(days=1)
    # 前一日的活跃结束日期为今日的0时0分  所以日期减少0天
    # end_time=now_date-timedelta(days=0)
    # 以此类推 循环30次即可
    active_time = []
    active_count = []
    for i in range(1, 31):
        bigin_time = now_date - timedelta(days=i)
        end_time = now_date - timedelta(days=i - 1)
        active_time.append(bigin_time.strftime('%Y-%m-%d'))
        act_count = User.query.filter(User.is_admin == False, User.last_login > bigin_time,
                                      User.last_login < end_time).count()
        active_count.append(act_count)
    # 得到的两个列表日期在前面的索引在前面  为符合需求 将列表反转
    active_time.reverse()
    active_count.reverse()
    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_time": active_time,
        "active_count": active_count
    }
    return render_template('admin/user_count.html', data=data)


@admin_blu.route('/logout')
def logout():
    """退出登录"""
    # session.pop('user_id')
    session.pop('nick_name')
    session.pop('mobile')
    session.pop('is_admin')
    return render_template('admin/login.html', errmsg="退出成功")


@admin_blu.route('/index', methods=['get', 'post'])
@user_login_data
def index():
    if not g.user:
        return redirect(url_for('admin.login'))
    data = {
        "user": g.user.to_dict()
    }
    return render_template('admin/index.html', data=data)


@admin_blu.route('/login', methods=['get', 'post'])
def login():
    """管理员登录"""
    if request.method == 'GET':
        # 如果已经登录，在访问登录页的时候直接跳转到后台管理主页
        user_id = session.get('user_id')
        is_admin = session.get('is_admin')
        if user_id and is_admin:
            return redirect(url_for('admin.index'))
        return render_template('admin/login.html')

    # 登录请求
    # 接收用户发送过来的参数
    mobile = request.form.get('username')
    password = request.form.get('password')
    if not all([mobile, password]):
        return render_template('admin/login.html', errmsg='参数错误')

    try:
        user = User.query.filter(User.mobile == mobile, User.is_admin == True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/login.html', errmsg='参数错误')

    if not user:
        return render_template('admin/login.html', errmsg='用户不存在')

    if not user.check_passowrd(password):
        return render_template('admin/login.html', errmsg='用户名或密码错误')

    # 代码执行到此说明用户可以登录，保持用户的登录状态
    session['user_id'] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    session['is_admin'] = user.is_admin

    # 登录成功之后  重定向到管理中心主页
    return redirect(url_for('admin.index'))
